package cn.base.web.auth.inner.realm;

import cn.base.web.auth.inner.token.InnerAuthToken;
import cn.base.web.config.LoginProperties;
import cn.rengy.auth.Authentication;
import cn.rengy.auth.AuthenToken;
import cn.rengy.auth.SimpleAuthenInfo;
import cn.rengy.auth.entity.principal.Identity;
import cn.rengy.auth.exception.AuthException;
import cn.rengy.auth.jwt.JwtCreator;
import cn.rengy.auth.realm.AbstractAuthenRealm;
import cn.rengy.util.web.RequestUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class InnerAuthenRealm extends AbstractAuthenRealm {
    @Override
    public String getName() {
        return "InnerAuthenRealm";
    }

    @Override
    public boolean supports(AuthenToken token) {
        return token.getClass() == InnerAuthToken.class;
    }


//    @Autowired
//    private LoginProperties loginProperties;


    @Override
    public Authentication getAuthenticationInfo(AuthenToken authenticationToken) throws AuthException {
        if (!supports(authenticationToken)) {
            log.error("error token: {}",authenticationToken.getClass().getName());
            throw new AuthException(401,"错误的token登陆");
        }
        //ExpiredCredentialsException 凭据已失效
        //IncorrectCredentialsException 凭据与主体不匹配
        InnerAuthToken innerAuthToken = (InnerAuthToken)authenticationToken;
        String token=innerAuthToken.getJwt();

        //解析jwt的payload
        Identity identity=null;
        try {
            identity= JwtCreator.parseToken(token);
        }catch(ExpiredJwtException e) {
            throw new AuthException(401,"token已过期");
        }catch(JwtException e) {
            log.warn("jwt解析错误：{}",e.getMessage());
            throw new AuthException(401,"jwt解析错误");
        }
        RequestUtil.setPrincipal(identity);
        return new SimpleAuthenInfo(identity,token,this.getName());
    }




}
